/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-07 13:44:19
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.joysuch.wwyt.api.dataaccess.DataAccessService;
import com.joysuch.wwyt.bp.bean.*;
import com.joysuch.wwyt.bp.bean.BpEmergencyTrainingDrillListBean.Search;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.entity.dsl.QBpEmergencyExercisePlan;
import com.joysuch.wwyt.bp.entity.dsl.QBpEmergencyExerciseRecord;
import com.joysuch.wwyt.bp.entity.dsl.QBpEmergencyTrainingDrill;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.bp.service.BpEmergencyTrainingDrillService;
import com.joysuch.wwyt.common.entity.CommonIndexNotify;
import com.joysuch.wwyt.common.enums.CommonIndexNotifyTypes;
import com.joysuch.wwyt.common.repository.CommonIndexNotifyDao;
import com.joysuch.wwyt.common.service.CommonIndexNotifyService;
import com.joysuch.wwyt.core.bean.BaseAttachmentBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.entity.BaseTypeGroupItem;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseImageRespositoryDao;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
@Slf4j
public class BpEmergencyTrainingDrillServiceImpl implements BpEmergencyTrainingDrillService {

    @Autowired
    private BpEmergencyTrainingDrillDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;

    @Autowired
    private BpEmergencyContingencyPlanDao bpEmergencyContingencyPlanDao;

    @Autowired
    private BpDepartDao bpDepartDao;

    @Autowired
    private BaseUserDao baseUserDao;

    @Autowired
    private BaseImageRespositoryDao baseImageRespositoryDao;
    @Autowired
    private BaseAttachmentRepositoryService attachmentService;

    @Autowired
    private BpEmergencyExercisePlanDao bpEmergencyExercisePlanDao;

    @Autowired
    private BpEmergencyContingencyPlansDao bpEmergencyContingencyPlansDao;

    @Autowired
    private BaseAttachmentRepositoryService attachmentRepositoryService;

    @Autowired
    private BpEmergencyExerciseRecordDao bpEmergencyExerciseRecordDao;

    @Autowired
    private BpEmergencyDefectDao bpEmergencyDefectDao;

    @Autowired
    private CommonIndexNotifyDao commonIndexNotifyDao;

    @Autowired
    private CommonIndexNotifyService commonIndexNotifyService;

    @Autowired
    private BaseTypeGroupItemDao baseTypeGroupItemDao;

    @Value("${wwyt.base.serverUrl}")
    private String serverUrl;
    @Autowired
    private DataAccessService dataAccessService;

    @Override
    public BpEmergencyTrainingDrill add(BpEmergencyTrainingDrillEditBean entity) throws Exception {
        String name = entity.getName();
        List<BpEmergencyTrainingDrill> tempList = dao.findByName(name);
        if (!CollectionUtils.isEmpty(tempList)) {
            throw new IllegalArgumentException("此名称已存在");
        }

        BpEmergencyTrainingDrill content = new BpEmergencyTrainingDrill();
        // 演练名称
        content.setName(entity.getName());
        // 演练编号
        content.setCode(bizCodeGeneratorFacade.peixunyanlian());
        // 预案ID
        content.setPlanId(entity.getPlanId());
        // 演练地点
        content.setDrillAddress(entity.getDrillAddress());
        // 组织部门ID
        content.setDepartId(entity.getDepartId());
        // 总指挥
        content.setCommander(entity.getCommander());
        // 演练时间
        if (entity.getDrillTimeStart() != null && entity.getDrillTimeEnd() != null) {
            Assert.isTrue(entity.getDrillTimeEnd().after(entity.getDrillTimeStart()), "演练结束时间必须大于开始时间");
        }
        content.setDrillTimeStart(entity.getDrillTimeStart());
        content.setDrillTimeEnd(entity.getDrillTimeEnd());
        // 参与部门和单位
        content.setPartakeDetail(entity.getPartakeDetail());
        // 实际演练部分
        content.setActualDrillPart(entity.getActualDrillPart());
        // 物质准备和人员培训情况
        content.setPreparationTrainCase(entity.getPreparationTrainCase());
        // 演练过程描述
        content.setDrillProcessDesc(entity.getDrillProcessDesc());
        // 存在的问题
        content.setIssuesDesc(entity.getIssuesDesc());
        // 改进措施
        content.setMendMeasure(entity.getMendMeasure());
        // 应急预案修改内容
        content.setPlanUpdateContent(entity.getPlanUpdateContent());
        // 图片附件ID
        if (entity.getAttachments() != null && entity.getAttachments().size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (BaseAttachmentBean bp : entity.getAttachments()) {
                sb.append(bp.getId()).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            content.setAttachmentId(sb.toString());
        }
        return dao.save(content);
    }

    // ，
    @Override
    public void update(BpEmergencyTrainingDrillEditBean entity) throws Exception {
        BpEmergencyTrainingDrill content = dao.findById(entity.getId()).get();
        if (content != null) {
            String name = entity.getName();
            if (!content.getName().equals(name)) {
                List<BpEmergencyTrainingDrill> tempList = dao.findByName(name);
                if (!CollectionUtils.isEmpty(tempList)) {
                    throw new IllegalArgumentException("此名称已存在");
                }
            }
            // ID，主键
            content.setId(entity.getId());
            // 演练名称
            content.setName(entity.getName());
            // 预案ID
            content.setPlanId(entity.getPlanId());
            // 演练地点
            content.setDrillAddress(entity.getDrillAddress());
            // 组织部门ID
            content.setDepartId(entity.getDepartId());
            // 总指挥
            content.setCommander(entity.getCommander());
            // 演练时间
            if (entity.getDrillTimeStart() != null && entity.getDrillTimeEnd() != null) {
                Assert.isTrue(entity.getDrillTimeEnd().after(entity.getDrillTimeStart()), "演练结束时间必须大于开始时间");
            }
            content.setDrillTimeStart(entity.getDrillTimeStart());
            content.setDrillTimeEnd(entity.getDrillTimeEnd());
            // 参与部门和单位
            content.setPartakeDetail(entity.getPartakeDetail());
            // 实际演练部分
            content.setActualDrillPart(entity.getActualDrillPart());
            // 物质准备和人员培训情况
            content.setPreparationTrainCase(entity.getPreparationTrainCase());
            // 演练过程描述
            content.setDrillProcessDesc(entity.getDrillProcessDesc());
            // 存在的问题
            content.setIssuesDesc(entity.getIssuesDesc());
            // 改进措施
            content.setMendMeasure(entity.getMendMeasure());
            // 应急预案修改内容
            content.setPlanUpdateContent(entity.getPlanUpdateContent());
            // 图片附件 ID 不为空，则更新附件 ID
            if (entity.getAttachments() != null && entity.getAttachments().size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (BaseAttachmentBean bp : entity.getAttachments()) {
                    sb.append(bp.getId()).append(",");
                }
                sb.deleteCharAt(sb.length() - 1);
                content.setAttachmentId(sb.toString());
            }
            dao.save(content);
        }
    }

    @Override
    public Page<BpEmergencyTrainingDrillListBean> findByPage(Pageable page, Search condition) throws ParseException {
        Predicate predicate = prepareListSearchCondition(condition);
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<BpEmergencyTrainingDrill> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);

        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpEmergencyTrainingDrillListBean, BpEmergencyTrainingDrill>() {

                    @Override
                    public BpEmergencyTrainingDrillListBean convert(BpEmergencyTrainingDrill f) {
                        BpEmergencyTrainingDrillListBean bean = new BpEmergencyTrainingDrillListBean();

                        // ID，主键
                        bean.setId(f.getId());
                        // 演练名称
                        bean.setName(f.getName());
                        // 演练编号
                        bean.setCode(f.getCode());
                        // 预案ID
                        bean.setPlanId(f.getPlanId());
                        bean.setPlanName(bpEmergencyContingencyPlanDao.findPlanNameById(f.getPlanId()));
                        // 演练地点
                        bean.setDrillAddress(f.getDrillAddress());
                        // 组织部门ID
                        bean.setDepartId(f.getDepartId());
                        bean.setDepartName(bpDepartDao.findDepartNameById(f.getDepartId()));
                        // 总指挥
                        bean.setCommander(f.getCommander());
                        // 演练时间
                        if (f.getDrillTimeStart() != null) {
                            bean.setDrillTimeStart(SimpleDateFormatCache.getYmdhms().format(f.getDrillTimeStart()));
                        }
                        if (f.getDrillTimeEnd() != null) {
                            bean.setDrillTimeEnd(SimpleDateFormatCache.getYmdhms().format(f.getDrillTimeEnd()));
                        }
                        // 参与部门和单位
                        bean.setPartakeDetail(f.getPartakeDetail());
                        // 实际演练部分
                        bean.setActualDrillPart(f.getActualDrillPart());
                        // 物质准备和人员培训情况
                        bean.setPreparationTrainCase(f.getPreparationTrainCase());
                        // 演练过程描述
                        bean.setDrillProcessDesc(f.getDrillProcessDesc());
                        // 存在的问题
                        bean.setIssuesDesc(f.getIssuesDesc());
                        // 改进措施
                        bean.setMendMeasure(f.getMendMeasure());
                        // 应急预案修改内容
                        bean.setPlanUpdateContent(f.getPlanUpdateContent());
                        // 附件对象 [附件 ID 、附件名称、下载地址]
                        if (f.getAttachmentId() != null && !"".equals(f.getAttachmentId())) {
                            String[] ss = f.getAttachmentId().split(",");
                            List<BaseAttachmentBean> list = new ArrayList<>(ss.length);
                            for (String s : ss) {
                                if (StringUtils.isNotBlank(s)) {
                                    BaseAttachmentBean attachment = attachmentService
                                            .findByIdIntoBean(Long.parseLong(s));
                                    list.add(attachment);
                                }
                            }
                            bean.setAttachments(list);
                            // bean.setBaseAttachmentBean(baseAttachmentBean);
                        }
                        return bean;
                    }

                });
    }

    private Predicate prepareListSearchCondition(Search condition) throws ParseException {
        QBpEmergencyTrainingDrill qEmeDrill = QBpEmergencyTrainingDrill.bpEmergencyTrainingDrill;
        Predicate predicate = null;
        if (condition.getName() != null) {
            predicate = qEmeDrill.name.contains(condition.getName());
        }
        if (condition.getDrillTimeStart() != null) {
            predicate = ExpressionUtils.and(predicate, qEmeDrill.drillTimeStart.goe(condition.getDrillTimeStart()));
        }
        if (condition.getDrillTimeEnd() != null) {
            predicate = ExpressionUtils.and(predicate, qEmeDrill.drillTimeEnd.loe(condition.getDrillTimeEnd()));
        }
        return predicate;
    }

    @Override
    public void delete(Long id) throws BusinessRestrictionsException {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     *
     * @param id 要删除的业务ID
     * @throws BusinessRestrictionsException 抛出的业务异常
     */
    private void checkBussinessRestrictions(Long id) throws BusinessRestrictionsException {

    }

    @Override
    public BpEmergencyTrainingDrill findById(Long id) {
        return dao.findById(id).get();
    }

    /**
     * 新增演练计划
     *
     * @param bean
     * @return
     */
    @Override
    public BpEmergencyExercisePlan saveExercisePlan(BpEmergencyExercisePlanBean bean) throws ApiBusinessException {
        BpEmergencyExercisePlan plan = null;
        if (bean.getId() == null) {
            List<BpEmergencyExercisePlan> epList = bpEmergencyExercisePlanDao.findByName(bean.getName());
            if (!CollectionUtils.isEmpty(epList)) {
                throw new ApiBusinessException(Status.NAME_WAS_EXIST, bean.getName());
            }
            plan = new BpEmergencyExercisePlan();
            plan.setCode(bizCodeGeneratorFacade.yingjiyuan());
        } else {
            List<BpEmergencyExercisePlan> epList = bpEmergencyExercisePlanDao.findByNameAndIdNot(bean.getName(), bean.getId());
            if (!CollectionUtils.isEmpty(epList)) {
                throw new ApiBusinessException(Status.NAME_WAS_EXIST, bean.getName());
            }
            plan = bpEmergencyExercisePlanDao.getOne(bean.getId());
        }
        plan.setName(bean.getName());
        plan.setLocation(bean.getLocation());
        plan.setDepartId(bean.getDepartId());
        plan.setMethod(bean.getMethod());
        plan.setLevel(bean.getLevel());
        plan.setPid(bean.getPId());
        plan.setDesigenerId(bean.getDesigenerId());
        plan.setEnacymentDate(bean.getEnacymentDate());
        plan.setStartDate(bean.getStartDate());
        plan.setEndDate(bean.getEndDate());
        plan.setContent(bean.getContent());
        plan.setNote(bean.getNote());
        plan.setAttachmentId(extractPlanAttachmentIds(bean));
        BpEmergencyExercisePlan savePlan = bpEmergencyExercisePlanDao.save(plan);
        //应急成员通知
        notifyPlan(savePlan.getId());
        return savePlan;

    }

    /**
     * 作废演练计划
     *
     * @param id
     * @return
     */
    @Override
    public void deleteExercisePlan(Long id) {
        bpEmergencyExercisePlanDao.deleteById(id);
    }

    /**
     * 查看演练计划
     *
     * @param id
     * @return
     */
    @Override
    public BpEmergencyExercisePlanBean getExercisePlan(Long id) {
        Optional<BpEmergencyExercisePlan> erp = bpEmergencyExercisePlanDao.findById(id);
        if (!erp.isPresent()) {
            throw new IllegalArgumentException("数据不存在");
        }
        BpEmergencyExercisePlan plan = erp.get();
        BpEmergencyExercisePlanBean bean = new BpEmergencyExercisePlanBean();
        bean.setId(plan.getId());
        bean.setName(plan.getName());
        bean.setLocation(plan.getLocation());
        bean.setDepartId(plan.getDepartId());
        if (plan.getDepartId() != null) {
            Optional<BpDepart> obd = bpDepartDao.findById(plan.getDepartId());
            if (obd.isPresent()) {
                bean.setDepartName(obd.get().getName());
            }
        }
        bean.setMethod(plan.getMethod());
        //演练方式
        if (plan.getMethod() != null) {
            Optional<BaseTypeGroupItem> byId = baseTypeGroupItemDao.findById(plan.getMethod());
            if (byId.isPresent()) {
                bean.setMethodName(byId.get().getName());
            } else {
                bean.setMethodName("");
            }
        }
        //演练级别
        bean.setLevel(plan.getLevel());
        if (plan.getLevel() != null) {
            Optional<BaseTypeGroupItem> byId = baseTypeGroupItemDao.findById(plan.getLevel());
            if (byId.isPresent()) {
                bean.setLevelName(byId.get().getName());
            } else {
                bean.setLevelName("");
            }
        }
        bean.setPId(plan.getPid());
        if (plan.getPid() != null) {
            Optional<BpEmergencyContingencyPlans> obp = bpEmergencyContingencyPlansDao.findById(plan.getPid());
            if (obp.isPresent()) {
                bean.setPName(obp.get().getName());
            }
        }
        bean.setDesigenerId(plan.getDesigenerId());
        if (plan.getDesigenerId() != null) {
            Optional<BaseUser> obu = baseUserDao.findById(plan.getDesigenerId());
            if (obu.isPresent()) {
                bean.setDesigenerName(obu.get().getRealName());
            }
        }
        bean.setEnacymentDate(plan.getEnacymentDate());
        bean.setStartDate(plan.getStartDate());
        bean.setEndDate(plan.getEndDate());
        bean.setContent(plan.getContent());
        bean.setNote(plan.getNote());
        bean.setAttachments(findManyAttachmentByIdGroup(plan.getAttachmentId()));
        return bean;
    }

    /**
     * 分页查询演练计划
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public Page<BpEmergencyExercisePlanBean> pageExercisePlan(Pageable page, BpEmergencyExercisePlanBean.Search condition) {
        Predicate predicate = prepareListSearchConditionExercisePlan(condition);
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<BpEmergencyExercisePlan> data = predicate == null ? bpEmergencyExercisePlanDao.findAll(page) : bpEmergencyExercisePlanDao.findAll(predicate, page);
        return PageDataUtils.convertPageData(data, new PageDataConvert<BpEmergencyExercisePlanBean, BpEmergencyExercisePlan>() {
            @Override
            public BpEmergencyExercisePlanBean convert(BpEmergencyExercisePlan baseConfig) {
                BpEmergencyExercisePlanBean bean = new BpEmergencyExercisePlanBean();
                BeanUtils.copyProperties(baseConfig, bean);
                if (bean.getDepartId() != null) {
                    Optional<BpDepart> obd = bpDepartDao.findById(bean.getDepartId());
                    if (obd.isPresent()) {
                        bean.setDepartName(obd.get().getName());
                    }
                } else {
                    bean.setDepartName(null);
                }

                if (baseConfig.getPid() != null) {
                    Optional<BpEmergencyContingencyPlans> ocp = bpEmergencyContingencyPlansDao.findById(baseConfig.getPid());
                    if (ocp.isPresent()) {
                        bean.setPName(ocp.get().getName());
                    }
                }
                //演练方式
                if (baseConfig.getMethod() != null) {
                    Optional<BaseTypeGroupItem> byId = baseTypeGroupItemDao.findById(baseConfig.getMethod());
                    if (byId.isPresent()) {
                        bean.setMethodName(byId.get().getName());
                    } else {
                        bean.setMethodName("");
                    }
                }
                //演练级别
                if (baseConfig.getLevel() != null) {
                    Optional<BaseTypeGroupItem> byId = baseTypeGroupItemDao.findById(baseConfig.getLevel());
                    if (byId.isPresent()) {
                        bean.setLevelName(byId.get().getName());
                    } else {
                        bean.setLevelName("");
                    }
                }
                return bean;
            }
        });
    }

    /**
     * 新增演练记录
     *
     * @param bean
     * @return
     */
    @Override
    public BpEmergencyExerciseRecord addRecord(BpEmergencyExerciseRecordBean bean) {
        BpEmergencyExerciseRecord record = new BpEmergencyExerciseRecord();
        boolean flag = false;
        if (bean.getId() != null) {
            record = bpEmergencyExerciseRecordDao.getOne(bean.getId());
            flag = true;
        }
        if (bean.getCode() == null) {
            record.setCode(bizCodeGeneratorFacade.yanLianJiLu());
        }
        record.setName(bean.getName());
        record.setEpId(bean.getEpId());
        // record.setEpName(bpEmergencyExercisePlanDao.findById(record.getEpId()).get().getName());
        record.setEpName(bean.getEpName());
        record.setDate(bean.getDate());
        List<Long> iList = new ArrayList<>();
        List<Long> pList = new ArrayList<>();
        List<Long> dList = new ArrayList<>();
        //将实施人员,参演人员.参演部门id拼接成字符串存入数据库
        if (bean.getImplementerId().size() > 0) {
            for (BpBaseUserBean uBean : bean.getImplementerId()) {
                iList.add(uBean.getId());
            }
        }
        record.setImplementerId(longListToString(iList));
        if (bean.getParticipantId().size() > 0) {
            for (BpBaseUserBean uBean : bean.getParticipantId()) {
                pList.add(uBean.getId());
            }
        }
        record.setParticipantId(longListToString(pList));
        if (bean.getDepartId().size() > 0) {
            for (BpAddDepartBean dBean : bean.getDepartId()) {
                dList.add(dBean.getId());
            }
        }
        record.setDepartId(longListToString(dList));
        record.setContent(bean.getContent());
        record.setGoal(bean.getGoal());
        record.setProcess(bean.getProcess());
        record.setSummary(bean.getSummary());
        record.setOpinion(bean.getOpinion());
        //设置待整改
        record.setState(0);
        record.setAttachmentId(extractRecordAttachmentIds(bean));
        BpEmergencyExerciseRecord save = bpEmergencyExerciseRecordDao.save(record);
        List<BpEmergencyDefectBean> defectBeans = bean.getDefectBean();
        if (flag) {
            if (!CollectionUtils.isEmpty(bean.getDefectIds())) {
                bpEmergencyDefectDao.deleteByIds(bean.getDefectIds());
            }
            for (BpEmergencyDefectBean be : defectBeans) {
                BpEmergencyDefect bpEmergencyDefect = new BpEmergencyDefect();
                if (be.getId() != null) {
                    Optional<BpEmergencyDefect> re = bpEmergencyDefectDao.findById(be.getId());
                    if (re.isPresent()) {
                        bpEmergencyDefect = re.get();
                    }
                }
                BeanUtils.copyProperties(be, bpEmergencyDefect);
                if (bpEmergencyDefect.getState() == null) {
                    if (be.getCorrect().equals("是")) {
                        //需要整改,处理状态改为待整改
                        bpEmergencyDefect.setState(0);
                    } else {
                        //不需要整改,处理状态改为无需整改
                        bpEmergencyDefect.setState(2);
                    }
                }
                bpEmergencyDefect.setRecordId(save.getId());
                bpEmergencyDefectDao.save(bpEmergencyDefect);
            }
            int c = bpEmergencyDefectDao.countByRecordIdAndState(save.getId(), 0);
            save.setAccount(c);
            int count = bpEmergencyDefectDao.countByRecordId(save.getId());
            if (count == 0) {
                //没有整改记录,演练记录状态为无需整改
                save.setState(2);
            } else {
                if (c > 0) {
                    save.setState(0);
                } else {
                    int count1 = bpEmergencyDefectDao.countByRecordIdAndState(save.getId(), 1);
                    if (count1 > 0) {
                        save.setState(1);
                    } else {
                        save.setState(2);
                    }
                }
            }
            BpEmergencyExerciseRecord result = bpEmergencyExerciseRecordDao.save(save);
            return result;
        } else {
            if (defectBeans != null && defectBeans.size() > 0) {
                for (BpEmergencyDefectBean deBean : defectBeans) {
                    BpEmergencyDefect bpEmergencyDefect = new BpEmergencyDefect();
                    bpEmergencyDefect.setId(deBean.getId());
                    bpEmergencyDefect.setDescription(deBean.getDescription());
                    bpEmergencyDefect.setCorrect(deBean.getCorrect());
                    bpEmergencyDefect.setRecordId(save.getId());
                    if (deBean.getCorrect().equals("是")) {
                        //需要整改,处理状态改为待整改
                        bpEmergencyDefect.setState(0);
                    } else {
                        //不需要整改,处理状态改为无需整改
                        bpEmergencyDefect.setState(2);
                    }
                    bpEmergencyDefectDao.save(bpEmergencyDefect);
                }
            }
            int c = bpEmergencyDefectDao.countByRecordIdAndState(save.getId(), 0);
            save.setAccount(c);
            int count = bpEmergencyDefectDao.countByRecordId(save.getId());
            if (count == 0) {
                //没有整改记录,演练记录状态为无需整改
                save.setState(2);
            } else {
                int co = bpEmergencyDefectDao.countByRecordIdAndState(save.getId(), 2);
                if (count == co) {
                    //整改明细状态全为不需要整改,演练记录状态为无需整改
                    save.setState(2);
                }
            }
            BpEmergencyExerciseRecord result = bpEmergencyExerciseRecordDao.save(save);
            //调数据接入接口
            dataAccessService.emergencyExerciseRecord(result);
            return result;
        }
    }

//    /**
//     * 修改演练记录
//     *
//     * @param bean
//     * @return
//     */
//    @Override
//    public BpEmergencyExerciseRecord updateRecord(BpEmergencyExerciseRecordBean bean) {
//        if (bean.getId() == null) {
//            throw new IllegalArgumentException("演练记录不存在");
//        }
//        BpEmergencyExerciseRecord record = bpEmergencyExerciseRecordDao.findById(bean.getId()).get();
//        record.setId(bean.getId());
//        record.setEpId(bean.getEpId());
//        record.setEpName(bpEmergencyExercisePlanDao.findById(record.getEpId()).get().getName());
//        record.setDate(bean.getDate());
//        List<Long> iList = new ArrayList<>();
//        List<Long> pList = new ArrayList<>();
//        List<Long> dList = new ArrayList<>();
//        //将实施人员,参演人员.参演部门id拼接成字符串存入数据库
//        if (bean.getImplementerId().size() > 0) {
//            for (BpBaseUserBean uBean : bean.getImplementerId()) {
//                iList.add(uBean.getId());
//            }
//        }
//        record.setImplementerId(longListToString(iList));
//
//        if (bean.getParticipantId().size() > 0) {
//            for (BpBaseUserBean uBean : bean.getParticipantId()) {
//                pList.add(uBean.getId());
//            }
//        }
//        record.setParticipantId(longListToString(pList));
//
//        if (bean.getDepartId().size() > 0) {
//            for (BpAddDepartBean dBean : bean.getDepartId()) {
//                dList.add(dBean.getId());
//            }
//        }
//        record.setDepartId(longListToString(dList));
//
//        record.setContent(bean.getContent());
//        record.setGoal(bean.getGoal());
//        record.setProcess(bean.getProcess());
//        record.setSummary(bean.getSummary());
//        record.setOpinion(bean.getOpinion());
//        record.setAttachmentId(extractAttachmentIds(bean));
//        //修改整改表
//        List<BpEmergencyDefectBean> defectBeans = bean.getDefectBean();
//        Boolean flag = true;
//        if (defectBeans != null && defectBeans.size() > 0) {
//            for (BpEmergencyDefectBean deBean : defectBeans) {
//                if (deBean.getId() == null) {
//                    throw new IllegalArgumentException("整改计划不存在");
//                }
//                BpEmergencyDefect bpEmergencyDefect = bpEmergencyDefectDao.findById(deBean.getId()).get();
//                bpEmergencyDefect.setId(deBean.getId());
//                bpEmergencyDefect.setDescription(deBean.getDescription());
//                bpEmergencyDefect.setCorrect(deBean.getCorrect());
//                bpEmergencyDefect.setRecordId(bean.getId());
//                //如果有需要整改的
//                if (deBean.getCorrect() == 0) {
//                    flag = false;
//                }
//                bpEmergencyDefectDao.save(bpEmergencyDefect);
//            }
//        } else {
//            //无整改内容,演练记录状态->已完成
//            record.setState(2);
//        }
//        //原来演练记录状态:已整改;整改记录修改内容有需要整改的->演练记录状态改为待整改
//        if (record.getState() == 1 && flag == false) {
//            record.setState(0);
//        } else if (record.getState() == 0 && flag == true) {
//            //原来演练记录状态:待整改;整改记录修改内容无需要整改的->演练记录状态改为已整改
//            record.setState(1);
//        }
//
//        return bpEmergencyExerciseRecordDao.save(record);
//    }

    /**
     * 查看演练记录
     *
     * @param id
     * @return
     */
    @Override
    public BpEmergencyExerciseRecordBean getRecord(Long id) {
        Optional<BpEmergencyExerciseRecord> oer = bpEmergencyExerciseRecordDao.findById(id);
        if (!oer.isPresent()) {
            throw new IllegalArgumentException("数据不存在");
        }
        BpEmergencyExerciseRecord record = oer.get();
        BpEmergencyExerciseRecordBean bean = new BpEmergencyExerciseRecordBean();
        BeanUtils.copyProperties(record, bean);
        if (record.getEpId() != null) {
            Optional<BpEmergencyExercisePlan> byId = bpEmergencyExercisePlanDao.findById(record.getEpId());
            if (byId.isPresent()) {
                bean.setEpName(byId.get().getName());
            }
        }
        bean.setDate(record.getDate());
        String implementerId = record.getImplementerId();
        if (StringUtils.isNotBlank(implementerId)) {
            String[] iString = implementerId.split(",");
            List<BpBaseUserBean> uList = new ArrayList<>();
            for (int j = 0; j < iString.length; j++) {
                Optional<BaseUser> io = baseUserDao.findById(Long.valueOf(iString[j].trim()));
                if (io.isPresent()) {
                    BpBaseUserBean bpBaseUserBean = new BpBaseUserBean();
                    bpBaseUserBean.setId(io.get().getId());
                    bpBaseUserBean.setName(io.get().getRealName());
                    uList.add(bpBaseUserBean);
                } else {
                    uList.add(null);
                }
            }
            bean.setImplementerId(uList);
        } else {
            bean.setImplementerId(null);
        }

        String participantId = record.getParticipantId();
        if (StringUtils.isNotBlank(participantId)) {
            String[] pString = participantId.split(",");
            List<BpBaseUserBean> pList = new ArrayList<>();
            for (int j = 0; j < pString.length; j++) {
                Optional<BaseUser> po = baseUserDao.findById(Long.valueOf(pString[j].trim()));
                if (po.isPresent()) {
                    BpBaseUserBean bpBaseUserBean = new BpBaseUserBean();
                    bpBaseUserBean.setId(po.get().getId());
                    bpBaseUserBean.setName(po.get().getRealName());
                    pList.add(bpBaseUserBean);
                } else {
                    pList.add(null);
                }
            }
            bean.setParticipantId(pList);
        } else {
            bean.setParticipantId(null);
        }

        String DepartId = record.getDepartId();
        if (StringUtils.isNotBlank(DepartId)) {
            String[] dString = DepartId.split(",");
            List<BpAddDepartBean> dList = new ArrayList<>();
            for (int j = 0; j < dString.length; j++) {
                Optional<BpDepart> bpo = bpDepartDao.findById(Long.valueOf(dString[j].trim()));
                if (bpo.isPresent()) {
                    BpAddDepartBean bpAddDepartBean = new BpAddDepartBean();
                    bpAddDepartBean.setId(bpo.get().getId());
                    bpAddDepartBean.setName(bpo.get().getName());
                    dList.add(bpAddDepartBean);
                } else {
                    dList.add(null);
                }
            }
            bean.setDepartId(dList);
        } else {
            bean.setDepartId(null);
        }
        bean.setStateName(this.getStateName(record.getState()));
        bean.setAttachments(findManyAttachmentByIdGroup(record.getAttachmentId()));
        //查询整改计划
        List<BpEmergencyDefect> rList = bpEmergencyDefectDao.findByRecordId(record.getId());
        if (rList != null && rList.size() > 0) {
            List<BpEmergencyDefectBean> rbList = new ArrayList<>();
            for (BpEmergencyDefect bed : rList) {
                BpEmergencyDefectBean bpEmergencyDefectBean = new BpEmergencyDefectBean();
                bpEmergencyDefectBean.setId(bed.getId());
                bpEmergencyDefectBean.setCorrect(bed.getCorrect());
                bpEmergencyDefectBean.setDescription(bed.getDescription());
                bpEmergencyDefectBean.setStateName(this.getStateName(bed.getState()));
                rbList.add(bpEmergencyDefectBean);
            }
            bean.setDefectBean(rbList);
        } else {
            bean.setDefectBean(null);
        }
        return bean;
    }

    /**
     * 分页查看演示记录
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public Page<BpEmergencyExerciseRecordBean> pageRecord(Pageable page, BpEmergencyExerciseRecordBean.Search condition) {
        Predicate predicate = prepareListSearchConditionExerciseRecord(condition);
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<BpEmergencyExerciseRecord> data = predicate == null ? bpEmergencyExerciseRecordDao.findAll(page) : bpEmergencyExerciseRecordDao.findAll(predicate, page);
        return PageDataUtils.convertPageData(data, new PageDataConvert<BpEmergencyExerciseRecordBean, BpEmergencyExerciseRecord>() {
            @Override
            public BpEmergencyExerciseRecordBean convert(BpEmergencyExerciseRecord baseConfig) {
                BpEmergencyExerciseRecordBean bean = new BpEmergencyExerciseRecordBean();
                BeanUtils.copyProperties(baseConfig, bean);
                //bean.setEpName(bpEmergencyExercisePlanDao.findById(bean.getEpId()).get().getName());
                if (baseConfig.getEpId() != null) {
                    Optional<BpEmergencyExercisePlan> bp = bpEmergencyExercisePlanDao.findById(baseConfig.getEpId());
                    if (bp.isPresent()) {
                        bean.setEpName(bp.get().getName());
                    }
                }
                bean.setStateName(getStateName(bean.getState()));
                // 显示参演部门名称
                String DepartId = baseConfig.getDepartId();
                StringBuilder sb = new StringBuilder();
                if (StringUtils.isNotBlank(DepartId)) {
                    String[] dString = DepartId.split(",");
                    List<BpAddDepartBean> dList = new ArrayList<>();
                    for (int j = 0; j < dString.length; j++) {
                        Optional<BpDepart> bpo = bpDepartDao.findById(Long.valueOf(dString[j].trim()));
                        if (bpo.isPresent()) {
                            BpAddDepartBean bpAddDepartBean = new BpAddDepartBean();
                            bpAddDepartBean.setId(bpo.get().getId());
                            bpAddDepartBean.setName(bpo.get().getName());
                            dList.add(bpAddDepartBean);
                            sb.append(bpo.get().getName()).append(",");
                        } else {
                            dList.add(null);
                            sb.append("");
                        }
                    }
                    bean.setDepartId(dList);
                    if (sb.length() > 0) {
                        sb.deleteCharAt(sb.length() - 1);
                        bean.setDepartName(sb.toString());
                    }
                } else {
                    bean.setDepartId(null);
                    bean.setDepartName("");
                }
                return bean;
            }
        });
    }

    /**
     * 整改处理列表展示
     *
     * @param id
     * @return
     */
    @Override
    public List<BpEmergencyDefectBean> defect(Long id) {
        List<BpEmergencyDefect> rList = bpEmergencyDefectDao.findByRecordIdAndCorrect(id, "是");
        if (rList.size() > 0) {
            List<BpEmergencyDefectBean> rbList = new ArrayList<>();
            for (BpEmergencyDefect bed : rList) {
                BpEmergencyDefectBean bpEmergencyDefectBean = new BpEmergencyDefectBean();
                bpEmergencyDefectBean.setId(bed.getId());
                bpEmergencyDefectBean.setCorrect(bed.getCorrect());
                bpEmergencyDefectBean.setDescription(bed.getDescription());
                bpEmergencyDefectBean.setState(bed.getState());
                bpEmergencyDefectBean.setStateName(getStateName(bed.getState()));
                rbList.add(bpEmergencyDefectBean);
            }
            return rbList;
        } else {
            return null;
        }
    }

    /**
     * 整改操作
     *
     * @param id
     * @return
     */
    @Override
    public BpEmergencyDefect defectAction(Long id) {
        Optional<BpEmergencyDefect> obd = bpEmergencyDefectDao.findById(id);
        if (!obd.isPresent()) {
            log.error("BpEmergencyDefectId" + id + "数据为空");
            throw new IllegalArgumentException("系统繁忙，稍后再试");
        }
        BpEmergencyDefect defect = obd.get();
        //状态改为已处理
        defect.setState(1);
        BpEmergencyDefect de = bpEmergencyDefectDao.save(defect);
        //调整演练记录状态
        Optional<BpEmergencyExerciseRecord> oer = bpEmergencyExerciseRecordDao.findById(de.getRecordId());
        if (!oer.isPresent()) {
            log.error("演练记录不存在");
            throw new IllegalArgumentException("系统繁忙，稍后再试");
        }
        BpEmergencyExerciseRecord record = oer.get();
        //获取整改处理 待处理数量
        int count0 = bpEmergencyDefectDao.countByRecordIdAndState(de.getRecordId(), 0);
        if (count0 == 0) {
            record.setState(1);
        } else {
            record.setState(0);
        }
        return de;
    }

    /**
     * 应急通知
     *
     * @param id
     */
    @Override
    public void notifyPlan(Long id) {
        //获取演练计划
        Optional<BpEmergencyExercisePlan> oep = bpEmergencyExercisePlanDao.findById(id);
        if (!oep.isPresent()) {
            throw new IllegalArgumentException("演练计划不存在");
        }
        BpEmergencyExercisePlan exercisePlan = oep.get();
        Long pid = exercisePlan.getPid();
        if (pid != null) {
            Optional<BpEmergencyContingencyPlans> bcp = bpEmergencyContingencyPlansDao.findById(pid);
            if (bcp.isPresent()) {
                //获取预案
                BpEmergencyContingencyPlans contingencyPlan = bcp.get();
                String emergencyMember = contingencyPlan.getEmergencyMember();
                if (StringUtils.isNotBlank(emergencyMember)) {
                    //获取人员信息
                    String[] eString = emergencyMember.split(",");
                    for (int j = 0; j < eString.length; j++) {
                        Optional<BaseUser> bo = baseUserDao.findById(Long.valueOf(eString[j].trim()));
                        if (bo.isPresent()) {
                            BaseUser baseUser = bo.get();
                            CommonIndexNotify notify = new CommonIndexNotify();
                            notify.setType(CommonIndexNotifyTypes.URGENT_PLAN.getType());
                            notify.setReadFlag(0);
                            notify.setQueueOrNot(0);
                            notify.setRemindedOrNot(0);
                            //应急预案id
                            notify.setEduCertUserId(contingencyPlan.getId());
                            //到期提醒日期
                            notify.setRemindDate(LocalDate.now());
                            //到期提醒时间
                            notify.setRemindDateTime(LocalDateTime.now());
                            //人员id
                            notify.setUserId(baseUser.getId());
                            //提醒message格式：人+证书+日期+即将过期
                            String Message = baseUser.getRealName() + ",应急演练计划:" + exercisePlan.getName() + "(" + exercisePlan.getCode() + ")已制定,请注意查看";
                            notify.setNotifyMessage(Message);
                            commonIndexNotifyDao.save(notify);
                            commonIndexNotifyService.getNotify();
                        }
                    }
                }
            }

        }

    }

    /**
     * 删除演练记录
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean deleteRecord(Long id) {
        bpEmergencyExerciseRecordDao.deleteById(id);
        bpEmergencyDefectDao.deleteByRecordId(id);
        return ResultBean.defaultSuccessResult();
    }

    /**
     * 批量删除演练记录
     *
     * @param ids
     * @return
     */
    @Override
    public ResultBean deleteRecords(List<Long> ids) {
        bpEmergencyExerciseRecordDao.deleteByIds(ids);
        bpEmergencyDefectDao.deleteByRecordIds(ids);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public void updateRecord(Long id, Integer state) {
        BpEmergencyDefect bpEmergencyDefect = bpEmergencyDefectDao.findById(id).get();
        if (bpEmergencyDefect != null) {
            bpEmergencyDefect.setState(state);
        }
    }

    private Predicate prepareListSearchConditionExercisePlan(BpEmergencyExercisePlanBean.Search condition) {
        Predicate p = null;
        QBpEmergencyExercisePlan q = QBpEmergencyExercisePlan.BpEmergencyExercisePlan;
        //name为code和name
        if (condition.getCodeOrName() != null) {
            p = ExpressionUtils.and(p, ExpressionUtils.or(q.code.contains(condition.getCodeOrName()),
                    q.name.contains(condition.getCodeOrName())));
        }

        if (condition.getLevel() != null) {
            p = ExpressionUtils.and(p, q.level.eq(condition.getLevel()));
        }
        if (condition.getMethod() != null) {
            p = ExpressionUtils.and(p, q.method.eq(condition.getMethod()));
        }
        return p;
    }

    private Predicate prepareListSearchConditionExerciseRecord(BpEmergencyExerciseRecordBean.Search condition) {
        Predicate p = null;
        QBpEmergencyExerciseRecord q = QBpEmergencyExerciseRecord.BpEmergencyExerciseRecord;
        if (condition.getCodeOrEpName() != null) {
            p = ExpressionUtils.and(p, ExpressionUtils.or(q.code.contains(condition.getCodeOrEpName()),
                    q.epName.contains(condition.getCodeOrEpName())));
        }
        return p;
    }

    /**
     * 附件
     *
     * @param idGroupString
     * @return
     */
    private List<BaseAttachmentBean> findManyAttachmentByIdGroup(String idGroupString) {
        List<BaseAttachmentBean> list = new ArrayList<>(1);
        if (idGroupString != null) {
            String[] ids = idGroupString.split(",");
            for (String s : ids) {
                if (StringUtils.isNotBlank(s)) {
                    BaseAttachmentBean attachment = attachmentRepositoryService.findByIdIntoBean(Long.parseLong(s));
                    list.add(attachment);
                }
            }
        }
        return list;
    }

    /**
     * Long类型的list转String
     *
     * @param list
     * @return
     */
    private String longListToString(List<Long> list) {
        if (list.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i)).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } else {
            return null;
        }
    }


    /**
     * 演练记录附件上传处理
     *
     * @param entity
     */
    protected String extractRecordAttachmentIds(BpEmergencyExerciseRecordBean entity) {
        if (entity.getAttachments() != null && entity.getAttachments().size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (BaseAttachmentBean a : entity.getAttachments()) {
                sb.append(a.getId()).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        }
        return null;
    }

    /**
     * 演练计划附件上传处理
     *
     * @param entity
     */
    private String extractPlanAttachmentIds(BpEmergencyExercisePlanBean entity) {
        if (entity.getAttachments() != null && entity.getAttachments().size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (BaseAttachmentBean a : entity.getAttachments()) {
                sb.append(a.getId()).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        }
        return null;
    }

    //演练记录状态:0待整改;1已整改;2无需整改
    private String getStateName(Integer state) {
        if (state == 0) {
            return "待整改";
        } else if (state == 1) {
            return "已整改";
        } else if (state == 2) {
            return "无需整改";
        } else {
            return null;
        }
    }
}
